#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
import os
import sys
from Main import Main
import re
from DAC.BatimentDAC import Batiment
from DAC.AccessPointDAC import AccessPoint
from DAC.SalleDAC import Salle
from PythonUI.Ui_Page4 import Ui_Page4

class Page4(Ui_Page4,QtGui.QDialog):
    """
    Page de selection de l'AP.
    """
    def __init__(self,session):
        """
        Fonction d'initialisation
        """
        self.app = QtGui.QApplication(sys.argv)
        QtGui.QDialog.__init__(self)
        self.session=session
        self.parametre={}
        self.config={}
        self.error=1
                
    def recup_dico(self,filename):
        """
        Construction du dictionnaire d'AP depuis un fichier local
        """
        fichier=open(os.path.expanduser('~') + '/.GWA/' + filename,'r')
        expr=re.compile("[A-Za-z]")
        for line in fichier.readlines():
            if expr.findall(line):
                self.parametre[line.split(":")[0].split("\n")[0]]=line.split(":")[1].split("\n")[0]
        fichier.close()

    def suivant(self):
        """
        Fonction appele lors de la validation du bouton 'Ok'
        """
        if (self.lineEdit_nom.displayText() == ''):
            QtGui.QMessageBox.critical(self, "GWA", "Le nom de l'AP ne doit pas etre vide !", QtGui.QMessageBox.Ok)
            #On quitte la fonction
            return ''
        if (self.lineEdit_essid.displayText() == ''):
            QtGui.QMessageBox.critical(self, "GWA", "Le ESSID ne doit pas etre vide !", QtGui.QMessageBox.Ok)
            #On quitte la fonction
            return ''
        if (self.comboBox_reference.currentText() == '...'):
            QtGui.QMessageBox.critical(self, "GWA", "L'AP doit etre dans une salle !", QtGui.QMessageBox.Ok)
            #On quitte la fonction
            return ''
        indexAP = self.comboBox_AP.currentIndex()
        indexSA = self.comboBox_reference.currentIndex()
        MAC=self.lineEdit_addMAC.displayText()
        self.dico["nom"] = self.lineEdit_nom.displayText()
        self.dico["mac"] = MAC
        self.dico["x"] = int(self.doubleSpinBox_X.value())
        self.dico["y"] = int(self.doubleSpinBox_Y.value())
        self.dico["z"] = int(self.doubleSpinBox_Z.value())
        self.dico["essid"] = self.lineEdit_essid.displayText()
        self.dico["dhcp"]= ''
        self.dico["cryptage"]= ''
        self.dico["mobile"]= ''
        self.dico["geodescription"] = self.lineEdit_description.displayText()
      
        ap = AccessPoint()
        if(indexAP < 1):
            #On est sur 'Nouvel AP' on ajoute donc un nouvel AP dans la BDD
            ap.createByDico(self.dico)
            ap.insertToDb(self.listSA[indexSA-1]["ID"])
        else:
            #On effectue les modifs sur l'AP existant
            ap = AccessPoint(self.listAP[indexAP-1]["ID"])
            ap.createByDico(self.dico)
            ap.updateIntoDb(self.listSA[indexSA-1]["ID"])

        file=open(os.path.expanduser('~') + '/.GWA/dicoaccesspoint','a')
        file.write("\nnom:"+self.dico["nom"])
        file.write("\nmac:"+self.dico["mac"])
        file.write("\nx:"+str(self.dico["x"]))
        file.write("\ny:"+str(self.dico["y"]))
        file.write("\nz:"+str(self.dico["z"]))
        file.write("\nessid:"+self.dico["essid"])
        file.write("\nmobile:"+str(self.dico["mobile"]))
        file.write("\nid:"+ap.id["value"])
        file.write("\ncryptage:"+self.dico["cryptage"])
        file.write("\ndhcp:"+self.dico["dhcp"])
        file.write("\ngeodescription:"+self.dico["geodescription"])
        file.close()


        #Let's config
        #General
        config={}
        config["essid"]=self.lineEdit_essid.displayText()
        config["mac"]=MAC
        config["gw"]=""
        config["pilote"]=""    
        config["dhcp"]="1"
        config["ip"]=""
        config["masque"]=""
        config["cryptage"]=""
        config["cle"]=""
        self.close() 
         
        obj5=Main()
        obj5.func5(self.config)

    def displayAccessPoint(self):
        """
        Remplissage des champs de la fenetre depuis les infos de la BDD
        """
        indexAP = self.comboBox_AP.currentIndex()
        if indexAP >= 1    :
            self.pushButton_supprimer.setEnabled(True)
            self.lineEdit_nom.setText(self.listAP[indexAP-1]["nom"])
            self.lineEdit_essid.setText(self.listAP[indexAP-1]["essid"])
            self.lineEdit_addMAC.setText(self.listAP[indexAP-1]["mac"])
            self.doubleSpinBox_X.setValue(self.listAP[indexAP-1]["x"])
            self.doubleSpinBox_Y.setValue(self.listAP[indexAP-1]["y"])
            self.doubleSpinBox_Z.setValue(self.listAP[indexAP-1]["z"])
            self.lineEdit_description.setText(self.listAP[indexAP-1]["geodescription"])
            if self.listAP[indexAP-1]["mobile"] == "True":
                self.lineEdit_nom.setReadOnly(True)
                self.lineEdit_addMAC.setReadOnly(True)
                self.lineEdit_description.setReadOnly(True)                
            else:
                self.lineEdit_nom.setReadOnly(True)
                self.lineEdit_addMAC.setReadOnly(True)
                self.lineEdit_description.setReadOnly(True)
                self.doubleSpinBox_X.setReadOnly(True)
                self.doubleSpinBox_Y.setReadOnly(True)
                self.doubleSpinBox_Z.setReadOnly(True)
            
            i = 1
            for SA in self.listSA:
                if(self.listAP[indexAP-1]["link_sa"] == SA["ID"]):
                    self.comboBox_reference.setCurrentIndex(i)
                i = i+1
        else:
            self.pushButton_supprimer.setEnabled(False)
            self.lineEdit_nom.setText("")
            self.lineEdit_essid.setText("")
            self.lineEdit_addMAC.setText("")
            self.doubleSpinBox_X.setValue(0.0)
            self.doubleSpinBox_Y.setValue(0.0)
            self.doubleSpinBox_Z.setValue(0.0)
            self.comboBox_reference.setCurrentIndex(0)
            self.lineEdit_description.setText("")
            self.lineEdit_nom.setReadOnly(False)
            self.lineEdit_addMAC.setReadOnly(False)
            self.lineEdit_description.setReadOnly(False)
            self.doubleSpinBox_X.setReadOnly(False)
            self.doubleSpinBox_Y.setReadOnly(False)
            self.doubleSpinBox_Z.setReadOnly(False)
    
    def precedent(self):
        """
        Fonction appele lors de la validation du bouton 'precedent'
        """
        self.close()
        os.system("./Main.py 3")

    def affich(self,param):
        """
        Affichage de la fenetre
        """
        os.system("touch ~/.GWA/dicoaccesspoint")
        self.parametre=param
        self.setupUi(self)
        self.show()
        sys.exit(self.app.exec_())
    
    def maj_comboBox(self):
        """
        Mise a jour de la comboBox des AP
        """
        self.comboBox_AP.clear()
        self.comboBox_AP.addItem("Nouveau point d'acces")
        batiment = Batiment(self.parametre["id"])
        self.listAP = batiment.selectAccessPointFromDB()
        for AP in self.listAP:
            self.comboBox_AP.addItem(AP["nom"])

    def supprimer(self):
        """
        Suppression d'un AP
        """
        index_AP=self.comboBox_AP.currentIndex()
        ap_to_delete= AccessPoint(self.listAP[index_AP-1]['ID'])
        nb_enregistrements=ap_to_delete.deleteFromDb(self.listAP[index_AP-1]['link_sa'])
        self.maj_comboBox()
        self.comboBox_AP.setCurrentIndex(index_AP-1)

    def confirmation(self):
        """
        Confirmation de suppression d'un AP
        Appele en premier par le bouton de suppression.
        """
        index_SA=self.comboBox_reference.currentIndex()
        if index_SA >= 1:
            reply = QtGui.QMessageBox.question(self, 'GWA',"Etes vous sur de vouloir supprimer cette salle ?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                self.supprimer()
            else:
                pass

    def setupUi(self,Dialog):
        """
        Definition de l'interface graphique.
        La majorite de cette fonction est decrite dans le fichier genere par pyuic4 dans PythonUI/...
        """
        self.dico ={}
        self.parametre={}
        self.recup_dico("dicobatiment")
        batiment = Batiment(self.parametre["id"])
        Ui_Page4.setupUi(self,Dialog)
        self.comboBox_AP.addItem("Nouveau point d'acces")
        self.comboBox_reference.addItem("...")
        self.listAP = batiment.selectAccessPointFromDB()
        for AP in self.listAP:
            self.comboBox_AP.addItem(AP["nom"])
        self.listSA = batiment.selectSallesFromDB()
        for SA in self.listSA:   
            self.comboBox_reference.addItem(SA["nom"])
        self.pushButton_supprimer.setEnabled(False)
        self.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.suivant)
        self.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.precedent)
        self.connect(self.comboBox_AP, QtCore.SIGNAL("currentIndexChanged(int)"), self.displayAccessPoint)
        self.connect(self.pushButton_supprimer, QtCore.SIGNAL("clicked()"), self.confirmation)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
